package com.petdog.module.community.controller;

import com.petdog.common.dto.ApiResponse;
import com.petdog.common.dto.PageResult;
import com.petdog.module.community.dto.CommunityCreateRequest;
import com.petdog.module.community.dto.CommunityUpdateRequest;
import com.petdog.module.community.dto.CommunityDetailResponse;
import com.petdog.module.community.dto.CommunityListResponse;
import com.petdog.module.community.service.CommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.petdog.common.dto.PageResult;
import com.petdog.common.dto.ApiResponse;
import com.petdog.module.community.dto.CommunityCreateRequest;
import com.petdog.module.community.dto.CommunityDto;
import com.petdog.module.community.dto.CommunityUpdateRequest;
import com.petdog.module.community.service.CommunityService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 社区控制器
 */
@RestController
@RequestMapping("/api/community")
public class CommunityController {
    
    @Autowired
    private CommunityService communityService;
    
    /**
     * 创建社区
     */
    @PostMapping
    public ApiResponse<Long> createCommunity(@RequestBody CommunityCreateRequest request) {
        Long communityId = communityService.createCommunity(request);
        return ApiResponse.success(communityId);
    }
    
    /**
     * 更新社区信息
     */
    @PutMapping
    public ApiResponse<Boolean> updateCommunity(@RequestBody CommunityUpdateRequest request) {
        boolean success = communityService.updateCommunity(request);
        return success ? ApiResponse.success(true) : ApiResponse.error("更新失败");
    }
    
    /**
     * 删除社区
     */
    @DeleteMapping("/{communityId}")
    public ApiResponse<Boolean> deleteCommunity(@PathVariable Long communityId, @RequestParam Long userId) {
        boolean success = communityService.deleteCommunity(communityId, userId);
        return success ? ApiResponse.success(true) : ApiResponse.error("删除失败，只有创建者可以删除社区");
    }
    
    /**
     * 查询社区详情
     */
    @GetMapping("/{communityId}")
    public ApiResponse<CommunityDetailResponse> getCommunityDetail(@PathVariable Long communityId) {
        CommunityDetailResponse community = communityService.getCommunityDetail(communityId);
        return community != null ? ApiResponse.success(community) : ApiResponse.error("社区不存在");
    }
    
    /**
     * 分页查询社区列表
     * 支持结构化展示社区信息、关键词搜索社区
     */
    @GetMapping
    public ApiResponse<PageResult<CommunityListResponse>> getCommunityList(
            @RequestParam(defaultValue = "1") @Min(1) int page,
            @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size,
            @RequestParam(required = false) @Pattern(regexp = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{0,20}$", message = "搜索关键词只能包含中英文、数字，最多20个字符") String keyword) {
        try {
            // 参数校验通过后执行查询
            Map<String, Object> params = new HashMap<>();
            params.put("page", page);
            params.put("pageSize", size);
            params.put("offset", (page - 1) * size);
            params.put("keyword", keyword);
            
            // 使用CompletableFuture优化首屏加载性能，确保在2秒内完成
            CompletableFuture<List<CommunityListResponse>> dataFuture = CompletableFuture.supplyAsync(() ->
                    communityService.getCommunityList(params)
            );
            
            // 并行获取总条数
            CompletableFuture<Long> countFuture = CompletableFuture.supplyAsync(() ->
                    communityService.countCommunities(params)
            );
            
            // 设置超时，确保首屏加载≤2秒
            List<CommunityListResponse> communities = dataFuture.get(2, TimeUnit.SECONDS);
            long total = countFuture.get(2, TimeUnit.SECONDS);
            
            // 构建分页结果
            PageResult<CommunityListResponse> pageResult = new PageResult<>(communities, (int)total, page, size);
            
            // 根据不同情况返回不同的消息
            if (keyword != null && !keyword.trim().isEmpty()) {
                if (communities.isEmpty()) {
                    return ApiResponse.success(pageResult, "未找到'" + keyword + "'相关的社区");
                } else {
                    return ApiResponse.success(pageResult, "查询成功");
                }
            } else {
                if (communities.isEmpty()) {
                    return ApiResponse.success(pageResult, "暂无社区");
                } else {
                    return ApiResponse.success(pageResult, "查询成功");
                }
            }
        } catch (ExecutionException e) {
            // 处理执行异常
            Throwable cause = e.getCause();
            if (cause instanceof IllegalArgumentException) {
                return ApiResponse.error(cause.getMessage(), "INVALID_PARAMS");
            }
            return ApiResponse.error("服务器开小差了，请稍后再试", "SERVER_ERROR");
        } catch (java.util.concurrent.TimeoutException e) {
            // 处理超时异常
            return ApiResponse.error("获取社区列表超时，请稍后再试", "TIMEOUT_ERROR");
        } catch (Exception e) {
            // 处理其他异常
            return ApiResponse.error("可能由于网络原因暂时无法连接到服务器，请检查网络连接", "NETWORK_ERROR");
        }
    }
    
    /**
     * 搜索社区 - 专用搜索接口，确保搜索响应≤1秒
     */
    @GetMapping("/search")
    public ApiResponse<List<CommunityListResponse>> searchCommunities(
            @RequestParam @Pattern(regexp = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,20}$", message = "搜索关键词只能包含中英文、数字，1-20个字符") String keyword,
            @RequestParam(defaultValue = "1") @Min(1) int page,
            @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("page", page);
            params.put("pageSize", size);
            params.put("offset", (page - 1) * size);
            params.put("keyword", keyword);
            
            // 使用CompletableFuture优化搜索性能，确保在1秒内完成
            CompletableFuture<List<CommunityListResponse>> future = CompletableFuture.supplyAsync(() ->
                    communityService.searchCommunities(params)
            );
            
            // 设置超时，确保搜索响应≤1秒
            List<CommunityListResponse> communities = future.get(1, java.util.concurrent.TimeUnit.SECONDS);
            
            if (communities.isEmpty()) {
                return ApiResponse.success(communities, "未找到'" + keyword + "'相关的社区");
            }
            return ApiResponse.success(communities);
        } catch (ExecutionException e) {
            // 处理执行异常
            Throwable cause = e.getCause();
            if (cause instanceof IllegalArgumentException) {
                return ApiResponse.error(cause.getMessage(), "INVALID_PARAMS");
            }
            return ApiResponse.error("服务器开小差了，请稍后再试", "SERVER_ERROR");
        } catch (java.util.concurrent.TimeoutException e) {
            // 处理超时异常
            return ApiResponse.error("搜索超时，请稍后再试", "TIMEOUT_ERROR");
        } catch (Exception e) {
            // 处理其他异常
            return ApiResponse.error("可能由于网络原因暂时无法连接到服务器，请检查网络连接", "NETWORK_ERROR");
        }
    }
    
    /**
     * 获取热门社区
     */
    @GetMapping("/hot")
    public ApiResponse<List<CommunityListResponse>> getHotCommunities(@RequestParam(defaultValue = "10") Integer limit) {
        List<CommunityListResponse> communities = communityService.getHotCommunities(limit);
        return ApiResponse.success(communities);
    }
    
    /**
     * 获取用户加入的社区
     */
    @GetMapping("/user/{userId}")
    public ApiResponse<List<CommunityListResponse>> getUserCommunities(@PathVariable Long userId) {
        List<CommunityListResponse> communities = communityService.getUserCommunities(userId);
        return ApiResponse.success(communities);
    }
    
    /**
     * 判断用户是否已加入社区
     */
    @GetMapping("/{communityId}/check")
    public ApiResponse<Boolean> isUserInCommunity(@PathVariable Long communityId, @RequestParam Long userId) {
        boolean isIn = communityService.isUserInCommunity(userId, communityId);
        return ApiResponse.success(isIn);
    }
}
